var appPath = getAppPath();
var EDIT_IMG_IDX = 0;

/** 活动功能表 秒杀活动
 */
$(function(){
	//活动分类
	$("#boType").combobox({
		data:[{type_id:0,type_name:'不限'},{type_id:10,type_name:'秒杀活动'}],
		valueField:'type_id',
		textField:'type_name',
		value:0
	});
	
	//活动状态
	$("#boState").combobox({
		data:[
		      {type_id:0,type_name:'不限'},
		      {type_id:10,type_name:'未开始'},
		      {type_id:20,type_name:'进行中'},
		      {type_id:30,type_name:'已结束'}],
		valueField:'type_id',
		textField:'type_name',
		value:0
	});		
	
	$("#boPublish").combobox({
		data:[{type_id:-1,type_name:'不限'},{type_id:0,type_name:'未发布'},{type_id:1,type_name:'已发布'}],
		valueField:'type_id',
		textField:'type_name',
		value:-1
	});
	
	initactInfoGrid();
	initUploader();
});

/**初始化活动*/
function initactInfoGrid(){
	$('#actInfoGrid').datagrid({
	    url:appPath + "/itbActivity/getActivityInfo.action",
	    height:'full',
	    striped:true,
	    fitColumns:true,
	    nowrap: false,// 换行
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
	  		{field:'act_id',title:'活动ID',width:25,align:'center',sortable:false},
		    {field:'edit',title:'编辑',width:30,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		return "<a href='javascript:void(0)' onclick='showDetail("+rowData.act_id+")'>编辑</a>";
	        	}
		    },
	        {field:'type',title:'活动分类',width:40,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  var ret = '<span style="color:red">未知</span>';
		    			switch(Number(value||'0')){
		    				case 10: ret='<span style="color:#FF00FF;">秒杀活动</span>'; break;
		    			}
		    			return ret;
		    	  }
		      },
	        {field:'title',title:'活动标题',width:50,align:'left',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  var ret = '';
		    		  if(value){
		    			  ret = '<span style="color:green;">'+value+'</span>';
		    		  }
		    		  return ret;
		    	  }
		      },
		    {field:'start_time',title:'活动开始时间',width:55,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  return value||'<span style="color:red">未知</span>';
		    	  }
		      },
	        {field:'end_time',title:'活动结束时间',width:55,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		return value||'<span style="color:red>未知</span>"';
	        	}
		    },
		    {field:'state', title:'活动状态', width:35, align:'center', sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		var ret = '<span style="color:red">暂无</span>';
		    		switch(Number(value||'0')){
		    		case 10: ret='<span style="color:blue;">未开始</span>';break;
		    		case 20: ret='<span style="color:green;">进行中</span>';break;
		    		case 30: ret='<span style="color:red;">已结束</span>';break;
		    		}
		    		return ret;
		    	}
		    },
		    {field:'desc', title:'活动描述', width:60, align:'left', sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		return value||'<span style="color:red">暂无</span>';
		    	}
		    },
		    {field:'order', title:'排序', width:30, align:'center', sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		if(Number(value||'0')>=0){
		    			return '<a href="javascript:void(0)" onclick="editOrder('+rowData.act_id+','+value+')">'+value+'</a>';
		    		}
		    		return '';
		    	}
		    },
		    {field:'url', title:'活动链接', width:40, align:'left', sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		return value||'<span style="color:red">暂无</span>';
		    	}
		    },
		    {field:'add',title:'添加商品',width:30,align:'center',sortable:false,
		    	formatter:function(value, rowData, rowIndex){
		    		var itemCnt = Number(rowData.itemCnt||'0')||0;
		    		return "<a href='javascript:void(0)' onclick='showActGoods("+rowData.act_id+",\" "+rowData.title+"\")'>"+itemCnt+"件商品</a>";
		    	}
		    },
		    {field:'publish', title:'发布状态', width:35, align:'center', sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		var ret = '<span style="color:red;">N/A</span>';
		    		switch(Number(value||'0')){
		    		case 0: ret='<span style="color:red;">未发布</span>';break;
		    		case 1: ret='<span style="color:green;">已发布</span>'; break;
		    		}
		    		return ret;
		    	}
		    },
		    {field:'create_time',title:'创建时间',width:40,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:40,align:'left',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    pagination:true,
		rownumbers:true,
		toolbar:[
			{
				text:'新建活动',
				iconCls:'icon-add',
				handler:function(){
					addActivityInfo();
				}
			},
			{
				text:'删除活动',
				iconCls:'icon-cancel',
				handler:function(){
					delActInfo();
				}
			},
			{
				text:'发布活动',
				iconCls:'icon-ok',
				handler:function(){
					publishAct();
				}
			},
			{
				text:'取消发布',
				iconCls:'icon-cancel',
				handler:function(){
					cancelPublish();
				}
			}
		]
	});
}

/**活动商品信息*/
function initActItemInfoGrid(){
	var actId = 0;
	actId = $("#act_id").val();
	$('#actItemGrid').datagrid({
	    url:appPath + "/itbActivity/getActItemInfo.action?actId="+actId,
	    height:'full',
	    fit:true,
	    striped:true,
	    fitColumns:true,
	    nowrap: false,// 换行
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
	        {field:'r_id',title:'关联ID',width:30,align:'center',sortable:false},
		    {field : 'item_thumb',title : '商品图片',width : 50,align : 'center',sortable : false,
				formatter : function(value, rowData, rowIndex) {
					var retUrl = '';
	        		if (value) {
	        			retUrl = '<a href="' +rowData.item_thumb+ '" target="_blank">'
	        				+ '<div style="display:table;text-align:center;height:70px;width:70px;">'
	        				+ '<span align="center" style="display:table-cell;vertical-align:middle">'
	        				+ '<img src="'+rowData.item_thumb+'?x-oss-process=image/resize,m_lfit,h_100,w_100'
	        				+ '" style="display:inline;max-height:50px;max-width:50px;"/></span></div></a>';
	        		}
	        		return retUrl;
				}
		    },
		    {field:'item_id',title:'商品ID',width:30,align:'center',sortable:false},
	        {field:'item_name',title:'商品名称',width:50,align:'left',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  return '<span style="color:red;">'+value+'</span>'||'';
		    	  }
	        },
		    {field:'pp_name',title:'套餐名称',width:50,align:'left',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  return value||'<span style="color:red">未知</span>';
		    	  }
		    },
		    {field:'item_qty',title:'套餐数量',width:30,align:'center',sortable:false,
		    	formatter:function(value, rowData, rowIndex){
		    		var ret = '<span style="color:red;">0</span>';
		    		if(Number(value||'0')>0){
		    			ret = value;
		    		}
		    		return ret;
		    	}
		    },
		    {field:'item_unit',title:'单位',width:20,align:'center',sortable:false,
		    	formatter:function(value, rowData, rowIndex){
		    		return value||'<span style="color:red">未知</span>';
		    	}
		    },
		    {field:'act_price', title:'活动价', width:30, align:'center', sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		var show = '<span style="color:red">未知</span>';
	        		if(value>=0) {
	        			show = '<span style="color:red">'+(value/100)+'元</span>';
	        		}
	        		return show;
		    	}
		    },
	        {field:'org_price',title:'原价',width:30,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		var show = '<span style="color:red">未知</span>';
	        		if(value>=0) {
	        			show = '<span style="color:green">'+(value/100)+'元</span>';
	        		}
	        		return show;
	        	}
		    },
		    {field:'qty', title:'商品数量', width:35, align:'center', sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		var show = '<span style="color:red">未知</span>';
		    		if(value>=0) {
		    			show = '<span style="color:red">'+value+'</span>';
		    		}
		    		return show;
		    	}
		    },
		    {field:'rest_qty', title:'剩余数量', width:35, align:'center', sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		var show = '<span style="color:red">未知</span>';
		    		if(value>=0) {
		    			show = '<span style="color:green">'+value+'</span>';
		    		}
		    		return show;
		    	}
		    },
		    {field:'desc', title:'活动描述', width:50, align:'left', sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		return value||'';
		    	}
		    },
		    {field:'expiry_time', title:'截止日期', width:50, align:'center', sortable:false},
		    {field:'edit', title:'编辑', width:40, align:'center', sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		return '<a href="javascript:void(0)" onclick="editItem('+rowData.r_id+')">编辑</a>';
		    	}
		    },
		    {field:'create_time',title:'创建时间',width:40,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:40,align:'left',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    pagination:true,
		rownumbers:true,
		toolbar:[
			{
				text:'添加商品',
				iconCls:'icon-add',
				handler:function(){
					addItemInfo();
				}
			},
			{
				text:'删除商品',
				iconCls:'icon-cancel',
				handler:function(){
					delItemInfo();
				}
			}]
	});
}

//修改活动商品信息
function editItem(id){
	$("#itemActTable").show();
	$('#itemActForm').form('clear');
	$("#showItemBtn").hide();
	// 加载数据
	var url = appPath + "/itbActivity/getOneActivityRInfo.action?rId="+id;
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#itemId").attr('disabled','disabled');
			$("#itemId").val(info.item_id);
			$("#orgPrice").val(info.org_price);
			$("#actPrice").val(info.act_price);
			$("#itemQty").val(info.qty);
			$("#restQty").val(info.rest_qty);
			$('#ppId').attr('disabled','disabled');
			$('#ppId').val(info.pp_id);
			$('#ppMin').attr('disabled','disabled');
			$('#ppMin').val(info.item_qty);
			$('#ppUnit').attr('disabled','disabled');
			$('#ppUnit').val(info.item_unit);
			$('#expiryDate').datetimebox('setValue',info.expiry_time);
			$('#actItemDesc').val(info.desc);
		}
	});
	
	$('#addActItemDlg').window({
		title:'添加活动商品',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	initActItemInfoGrid();
	var actId = $("#act_id").val();
	$("#itActId").val(actId);
	$("#rId").val(id);
	$('#addActItemDlg').window('move',{top:20,left:20});
	$('#addActItemDlg').window('open');
}

//添加活动商品 选择页面
function addItemInfo(){
	$('#itemActForm').form('clear');
	$("#showItemBtn").show();
	$("#itemActTable").show();
	$("#itActId").val('');
	$("#itemActBtn").show();
	$('#itemId').attr('disabled','disabled');
	$('#ppId').attr('disabled','disabled');
	$('#ppMin').attr('disabled','disabled');
	$('#ppUnit').attr('disabled','disabled');
	$('#addActItemDlg').window({
		title:'添加活动商品',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	initActItemInfoGrid();
	var actId = $("#act_id").val();
	$("#itActId").val(actId);
	$('#addActItemDlg').window('move',{top:20,left:20});
	$('#addActItemDlg').window('open');
}

// 提交添加活动商品
function addActItem(){
	var itemId = Number($("#itemId").val()||'0')||0;//商品ID
	var ppId = Number($("#ppId").val()||'0')||0;//套餐ID
	var ppMin = Number($("#ppMin").val()||'0')||0;
	var ppUnit = $("#ppUnit").val();
	var actId = Number($("#itActId").val()||'0')||0;
	var rId = Number($("#rId").val()||'0')||0;
	var expiryDate = $("#expiryDate").datetimebox('getValue');//截止时间
	
	if(actId<=0) {
		$.messager.alert('提示信息','活动ID为空','info');
		return;
	}
	if(itemId<=0){
		$.messager.alert('提示信息','请选择一个商品','info');
		return;
	}
	if(ppId<=0){
		$.messager.alert('提示信息','请选择一个套餐','info');
		return;
	}
	if(ppMin<=0){
		$.messager.alert('提示信息','请选择一个套餐计价','info');
		return;
	}
	
	if(expiryDate==null || expiryDate.length<=0){
		$.messager.alert('提示信息','截止时间不能为空','info');
		return;
	}
	expiryDate = chkInputDate(expiryDate);
	if(expiryDate==null || expiryDate.length<=0){
		$.messager.alert('提示信息','请输入有效时间','info');
		return;
	}
	var orgPrice = Number($("#orgPrice").val()||'0')||0;//原价
	var actPrice = Number($("#actPrice").val()||'0')||0;//活动价
	var itemQty = Number($("#itemQty").val()||'0')||0;//商品数量
	var restQty = Number($("#restQty").val()||'0')||0;//剩余数量
	var desc = $("#actItemDesc").val();//描述
	
	if(orgPrice<0 || actPrice<0) {
		$.messager.alert('提示信息','商品价格异常','info');
		return;
	}
	
	if(itemQty<=0 || restQty<0) {
		$.messager.alert('提示信息','商品数量异常','info');
		return;
	}
	
	if(itemQty<restQty) {
		$.messager.alert('提示信息','商品剩余数量过大','info');
		return;
	}
	
	var url1 = appPath+"/itbActivity/addActivityItemInfo.action";//新建活动商品
	if(rId>0){
		url1 = appPath+"/itbActivity/updActivityRInfo.action";//修改活动商品
	}
	var sendData = {
		"activityRInfoDto.r_id": rId,
		"activityRInfoDto.act_id": actId,
		"activityRInfoDto.item_id": itemId,
		"activityRInfoDto.pp_id": ppId,
		"activityRInfoDto.item_qty": ppMin,
		"activityRInfoDto.item_unit": ppUnit || "",
		"activityRInfoDto.org_price": orgPrice,
		"activityRInfoDto.act_price": actPrice,
		"activityRInfoDto.qty": itemQty,
		"activityRInfoDto.rest_qty": restQty,
		"activityRInfoDto.expiry_time": expiryDate || "",
		"activityRInfoDto.desc": desc || ""
	};
    $.post(url1, sendData, function(data){  
		if (data == "ok") { 
			$.messager.alert('提示信息','提交成功','info');
			$('#addActItemDlg').window('close');
			$("#itemActForm").form('clear');
			doQuery2();
        }else {
        	$.message.alert("提示信息","提交失败",'info');
        }
    });			
}

// 取消添加活动商品
function celaddActItem(){
	$('#addActItemDlg').window('close');
	$("#itemActForm").form('clear');
}

// 展示商品
function showItem(){
	$("#itemsGrid").val('');
	$("#itemTable").show();
	var l = $("#queryTypeL").combobox('getValue');
	$("#queryTypeL").combobox({
		data:[
		      {type_id:0,type_name:'[不限]'},
		      {type_id:4,type_name:'印品'},
		      {type_id:5,type_name:'配件'},
		      {type_id:9,type_name:'虚拟商品'},
		      {type_id:1010,type_name:'Logo商品'},
		      {type_id:1011,type_name:'营销商品'}
        ],
		valueField:'type_id',
		textField:'type_name',
		value:l||0,
		onSelect:function(selRecdL){
			$("#queryTypeM").combobox("clear");
			$("#queryTypeM").combobox("loadData",{});
			$("#queryTypeS").combobox("clear");
			$("#queryTypeS").combobox("loadData",{});
			var topId=selRecdL.type_id;
			// 中分类
			$("#queryTypeM").combobox({
				url:appPath+'/itbTg/getTypeForCombo.action?blkFlg=1&parent='+topId,
				valueField:'type_id',
				textField:'type_name',
				onSelect:function(selRecdM){
					$("#queryTypeS").combobox("clear");
					$("#queryTypeS").combobox("loadData",{});
					// 小分类
					var parentId=selRecdM.type_id;
					if(Number(parentId)>0){
						$("#queryTypeS").combobox({
							url:appPath+'/itbTg/getTypeForCombo.action?blkFlg=1&parent='+parentId,
							valueField:'type_id',
							textField:'type_name',
							onSelect:function(selRecdS){
							}
						});
					}
				}
			});
		}
	});
	$("#itemBtn").show();
	$('#itemDlg').window({
		title:'商品详情',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	initItemsGrid();
	$('#itemDlg').window('move',{top:20,left:20});
	$('#itemDlg').window('open');
}

// 勾选商品
function chkItem(){
	var selectItem=$("#itemsGrid").datagrid("getChecked");//获取商品勾选的商品ID
	if(!selectItem || selectItem.length != 1){
		$.messager.alert('提示信息','请勾选单个需要添加的商品！','warning');
		return;
	}
//	var itemId = '';
//	$.each(selectItem, function(index, item){
//		itemId = item.item_id;
//	});
	
	var itemInfo = selectItem[0];
	if(itemInfo.top_type_id==1010){// LOGO
		var msg = '';
		if(itemInfo.saleCnt>0) {// 已售
			msg = "<span style='color:red'>该Logo商品已售出过!</br>是否确认再次销售？</span>";
		} else if(itemInfo.actCnt>0) {// 参与过活动
			msg = "<span style='color:red'>该Logo商品已参加过促销活动!</br>是否确认再次销售？</span>";
			if(itemInfo.pubActCnt>0) {
				msg = "<span style='color:red'>该Logo商品已参加发布中的促销活动!</br>是否确认再次销售？</span>";
			}
		}
		
		if(msg && msg.length>0) {
			$.messager.confirm("确认", msg,
				function(r){
			        if(r) {
			        	$.messager.confirm("确认", "<span style='color:green'>Are U Sure Baby ?!</span>",
		        			function(r2){
		        		        if(r2) { 
		        					//
		        		        	$("#itemId").val(itemInfo.item_id);
		        		        	$("#ppId").val('');// clear
		        		        	$("#ppMin").val('');// clear
		        		        	$("#ppUnit").val('');// clear
		        		        	$("#itemDlg").window('close');
		        		        }
		        			}
		        		);
			        }//
				}//
			);
			return;
		}
	}
	
	//
	$("#itemId").val(itemInfo.item_id);
	$("#ppId").val('');// clear
	$("#ppMin").val('');// clear
	$("#ppUnit").val('');// clear
	$("#itemDlg").window('close');
}

// 取消 勾选商品
function celchkItem(){
	$("#itemDlg").window('close');
}

// 获取商品参数
function getQueryParam3(){
	var queryObject = {};
	var findTypeL = $("#queryTypeL").combobox('getValue');
	var findTypeM = $("#queryTypeM").combobox('getValue');
	var findTypeS = $("#queryTypeS").combobox('getValue');
	var findNo = $("#queryItemNo").val();
	var findName = $("#queryItemName").val();
	var findTmplId = $("#queryTmplId").val();
	
	if(findTypeL && Number(findTypeL||'0')>0) queryObject.findItemTypeL = findTypeL;// 大分类
	if(findTypeM && Number(findTypeM||'0')>0) queryObject.findItemTypeM = findTypeM;// 中分类
	if(findTypeS && Number(findTypeS||'0')>0) queryObject.findItemType = findTypeS;// 小分类
	if(findNo && findNo.length>0) queryObject.findItemNo = findNo;// 编号
	if(findName && findName.length>0) queryObject.findItemName = findName;// 名称
	if(findTmplId && findTmplId.length>0) queryObject.findDesignId = findTmplId;// 模版id
	return queryObject;
}

/**查询商品*/
function doQuery1(startFlg){
	$("#itemsGrid").datagrid('unselectAll');
	if(startFlg==1){
		$("#itemsGrid").datagrid('load', getQueryParam3());
	} else {
		$("#itemsGrid").datagrid('reload', getQueryParam3());
	}
}

// 获取套餐
function showPP(){
	var itemId = $("#itemId").val();
	if(itemId==null || itemId.length<=0){
		$.messager.alert('提示信息','请选择商品！','info');
		return;
	}
	$("#ppBtn").show();
	$('#PpDlg').window({
		title:'商品套餐',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	initPpGrid();
	$('#PpDlg').window('move',{top:20,left:20});
	$('#PpDlg').window('open');
}

// 取消勾选套餐
function cancelChkPP(){
	$('#PpDlg').window('close');
	$("#PpForm").form('clear');
}

// 获取套餐计量单位
function showPpPrice(){
	var ppId = $("#ppId").val();
	if(ppId==null || ppId.length<=0){
		$.messager.alert('提示信息','请选择套餐！','info');
		return;
	}
	$("#priceBtn").show();
	$('#PpPriceDlg').window({
		title:'套餐价格计量',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	initPpPriceGrid();
	$('#PpPriceDlg').window('move',{top:20,left:20});
	$('#PpPriceDlg').window('open');
}

// 选择套餐
function chkPP(){
	var selectItem=$("#ppGrid").datagrid("getChecked");//获取商品勾选的商品ID
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请勾选一个套餐','warning');
		return;
	}
	var ppId = '';
	$.each(selectItem, function(index, item){
		ppId =item.pp_id;
	});
	$("#ppId").val(ppId);
	$("#ppMin").val('');// clear
	$("#ppUnit").val('');// clear
	$('#PpDlg').window('close');
	$("#PpForm").form('clear');
}

// 选择套餐数量价格计量
function chkPpPrice(){
	var selectItem=$("#ppPriceGrid").datagrid("getChecked");//获取商品勾选的商品ID
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请勾选套餐价格计量！','warning');
		return;
	}
	var minVal = '';
	var ppUnit = '';
	var ppPrice = 0;
	$.each(selectItem, function(index, item){
		minVal = item.min;
		ppUnit = item.unit;
		ppPrice = Number(item.price||'0');
	});
	$("#ppMin").val(minVal);
	$("#ppUnit").val(ppUnit);
	$("#orgPrice").val(ppPrice);// 默认原价
	$('#PpPriceDlg').window('close');
	$("#PpPrForm").form('clear');
}

// 取消套餐价格计量
function cancelChkPrice(){
	$('#PpPriceDlg').window('close');
	$("#PpPrForm").form('clear');
}


/**删除活动商品*/
function delItemInfo(){
	var selectItem=$("#actItemGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请勾选需要删除的内容！','warning');
		return;
	}
	$.messager.confirm("确认", "是否确认[删除]所选内容？",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectItem, function(index, item){
					ids = ids + item.r_id + ",";
				});
				if(ids){
					ids = ids.substring(0, ids.length-1);
					var url = appPath+"/itbActivity/delActivityRInfo.action?ids="+ids;
					$.post(url,function(data){
						if(data=="ok"){
							$.messager.alert('提示信息','删除成功','info');
							doQuery2();
						}else{
							$.messager.alert('提示信息','删除失败','info');
						}
					});
				}
				
	        }
		}
	);
}

// 展示活动商品
function showActGoods(id,title){
	$("#aItemForm").form('clear');
	$("#act_id").val(id);
	$('#actItemDlg').window({
		title:'活动商品',
		iconCls:'icon-edit',
		left:'300px',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	$("#pActId").html(id);
	$("#pTitle").html(title);
	initActItemInfoGrid();
	$('#actItemDlg').window('move',{top:0,left:20});
	$('#actItemDlg').window('open');
}


// 初始化 商品
function initItemsGrid(){
	$('#itemsGrid').datagrid({
	    url:appPath + "/itbActivity/getItemsInfoPg.action",
	    height:'80',
	    striped:true,
	    fitColumns:true,
	    fit:true,
	    queryParams: getQueryParam3(),
	    singleSelect:true,// 只允许选择一行
	    selectOnCheck:true,
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
  	        {field:'item_id',title:'商品ID',width:35,align:'center',sortable:false},
  	        {field:'item_no',title:'商品编号',width:50,align:'center',sortable:false},
  	        {field:'item_name',title:'商品名称',width:70,align:'center',sortable:false},
	        {field:'top_type_id',title:'大分类',width:40,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  var ret = '<span style="color:red">未知</span>';
		    			switch(Number(value||'0')){
		    				case 4: ret='<span style="color:red">印品</span>'; break;
		    				case 5: ret='<span style="color:blue">配件</span>'; break;
		    				case 9: ret='<span style="color:green">虚拟商品</span>'; break;
		    				case 1010: ret='<span style="color:green">Logo商品</span>'; break;
		    				case 1011: ret='<span style="color:green">营销商品</span>'; break;
		    			}
		    			return ret;
		    	  }
		      },
	        {field:'type_name',title:'商品分类',width:40,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  return value||'<span style="color:red">未知</span>';
		    	  }
		      },
	        {field:'design_id',title:'设计模版ID',width:45,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var show = '<span style="color:red">未关联</span>';
	        		if(Number(rowData.design_id||'0')>0){
	        			show = value;
	        		}
	        		return '<span style="color:blue;">'+show+'</span>';
	        	}
		    },
		    {field:'saleCnt',title:'销售',width:35,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var show = '<span style="color:blue">未售出</span>';
	        		if(Number(value||'0')>0) {
	        			show = '<span style="color:red">售出过</span>';
	        		}
	        		return show;
	        	}
		    },
		    {field:'actCnt',title:'促销活动',width:40,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var show = '<span style="color:blue">未参加过</span>';
	        		if(Number(value||'0')>0) {
	        			show = '<span style="color:red">参加过</span>';
	        		}
	        		return show;
	        	}
		    },
		    {field:'state',title:'状态',width:35,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.item_id) return "N/A";
	        		return getState4Show(value);
	        	}
		    },
	        {field:'create_time',title:'创建时间',width:45,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:45,align:'center',sortable:false}
	    ]],
	    pagination:true,
		rownumbers:true
	});
}


// 初始化 套餐
function initPpGrid(){
	var itemId = $("#itemId").val();
	$('#ppGrid').datagrid({
	    url:appPath + "/itbActivity/getItemComboInfo.action?itemId="+itemId,
	    height:'80',
	    striped:true,
	    fitColumns:true,
	    fit:true,
	    singleSelect:true,//只允许选择一行
	    selectOnCheck:true,
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
  	        {field:'pp_id',title:'套餐ID',width:35,align:'center',sortable:false},
  	        {field:'item_id',title:'商品编号',width:50,align:'center',sortable:false},
  	        {field:'itb_pp_name',title:'商品名称',width:70,align:'center',sortable:false}]],
	    pagination:false,
		rownumbers:true
	});
}

//初始化 套餐价格计量
function initPpPriceGrid(){
	var ppId = $("#ppId").val();
	$('#ppPriceGrid').datagrid({
	    url:appPath + "/itbActivity/getQtyPriceInfo.action?ppId="+ppId,
	    height:'80',
	    striped:true,
	    fitColumns:true,
	    fit:true,
	    singleSelect:true,//只允许选择一行
	    selectOnCheck:true,
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
  	        {field:'price_id',title:'价格ID',width:35,align:'center',sortable:false},
  	        {field:'pp_id',title:'套餐ID',width:50,align:'center',sortable:false},
  	        {field:'price',title:'套餐价格',width:50,align:'center',sortable:false},
  	        {field:'min',title:'数量',width:50,align:'center',sortable:false},
  	        {field:'unit',title:'单位',width:50,align:'center',sortable:false},
  	        {field:'desc',title:'套餐名',width:70,align:'center',sortable:false}]],
	    pagination:false,
		rownumbers:true
	});
}

function getState4Show(value){
	var state = '<span style="color:red">未知</span>';
	switch(Number(value||'0')){
		case 10: state='<span style="color:blue">编辑中</span>'; break;
		case 20: state='<span style="color:green">上架</span>'; break;
		case 30: state='<span style="color:red">下架</span>'; break;
	}
	return state;
}

/**发布活动*/
function publishAct(){
	var selectItem=$("#actInfoGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请勾选需要<发布>的活动！','warning');
		return;
	}
	if(selectItem.length > 1){
		$.messager.alert('提示信息','请勾选单个活动<发布>！','warning');
		return;
	}
	
	$.messager.confirm("确认", "是否确认发布？",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectItem, function(index, item){
					ids = ids + item.act_id + ",";
				});
				if(ids){
					ids = ids.substring(0, ids.length-1);
					var url = appPath+"/itbActivity/publishActInfo.action?ids="+ids+"&pu="+1;
					$.post(url,function(data){
						if(data=="ok"){
							// 更新api服务器redis
							// CLEAR
							var apiUrl1 = getApiServer()+"/lua/delActivity?actId="+ids;
							$.post(apiUrl1,function(ret1){
								if(ret1.success==1) {
									// ADD
									var apiUrl2 = getApiServer()+"/lua/addActivity?actId="+ids;
									$.post(apiUrl2,function(ret2){
										if(ret2.success==1) {
											$.messager.alert('提示信息','发布成功','info');
											doQuery();
										}else {
											$.messager.alert('提示信息','发布成功(但添加redis失败)','info');
											doQuery();
										}
									});
								} else {
									$.messager.alert('提示信息','发布成功(但清除redis失败)','info');
									doQuery();
								}
							});
						}else{
							$.messager.alert('提示信息','发布失败','info');
						}
					});
				}
				
	        }
		}
	);
}

/**取消发布互动
 */
function cancelPublish(){
	var selectItem=$("#actInfoGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请勾选需要<取消发布>的活动！','warning');
		return;
	}
	if(selectItem.length > 1){
		$.messager.alert('提示信息','请勾选单个活动取消<发布>！','warning');
		return;
	}
	$.messager.confirm("确认", "是否确认取消发布？",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectItem, function(index, item){
					ids = ids + item.act_id + ",";
				});
				if(ids){
					ids = ids.substring(0, ids.length-1);
					var url = appPath+"/itbActivity/publishActInfo.action?ids="+ids+"&pu="+0;
					$.post(url,function(data){
						if(data=="ok"){
							// 刷新redis
							var apiUrl = getApiServer()+"/lua/delActivity?actId="+ids;
							$.post(apiUrl,function(ret){
								if(ret.success==1) {
									$.messager.alert('提示信息','取消成功','info');
									doQuery();
								}else {
									$.messager.alert('提示信息','取消成功(但清除redis失败)','info');
									doQuery();
								}
							});
						}else{
							$.messager.alert('提示信息','取消失败','info');
						}
					});
				}
				
	        }
		}
	);
}

function cancelUpdOrder(){
	$("#orderDlg").window('close');
}

/**
 * 显示顺序
 */
function editOrder(stId, order){
	$("#orderStId").val(stId);
	$("#order").val(order);
	
	$("#orderBtn").show();
	$('#orderDlg').window({
		title:'显示顺序设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#orderDlg').window('move',{top:20,left:20});
	$('#orderDlg').window('open');
}

/**
 * 修改显示顺序
 */
function doUpdOrder(){
	var stId = $("#orderStId").val();
	var order = $("#order").val();
	if(!order || order.length == 0 || Number(order)>999 || Number(order)<=0){
		$.messager.alert('提示信息','有效数值范围为：1～999','warning');
		return;
	}
	
	var url = appPath+"/itbActivity/updActivityInfo.action";
	var sendData = {
			"activityInfoDto.act_id": stId,
			"activityInfoDto.order": order||""
		};
	$.post(url,sendData,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','显示顺序已更新！','info',function(){
				doQuery();
				$('#orderDlg').window('close');
			});
		}else {
			$.messager.alert('提示信息','显示顺序更新失败！','warning');
		}
	});
}
// 商品详细配图
function initUploader(){
	//var url = "http://upload.itbour.com/upload/user?device=101&user_type=0&user_id="+(g_userId||0);// 写DB
	var url = "http://upload.itbour.com/upload/?device=101&user_type=0&user_id="+(g_userId||0);// 不写DB
	var option = {};
    option.id = 'selImgFile';
    option.url = url;
    option.callback = function(res){
    	if(!res.success){
    		alert(res.msg);
            return;
    	}
    	if(res && res.data && res.data.url && res.data.url.length>0){
    		EDIT_IMG_IDX = Number(EDIT_IMG_IDX||0)+1;
    		var showImg = res.data.url+'?x-oss-process=image/resize,m_pad,h_180,w_180,color_cccccc';
			var imgHtml = '<div style="margin:8px;" id="editImg_'+EDIT_IMG_IDX+'">'+
				'<a href="' + res.data.url + '" target="_blank" id="editImg_a_'+EDIT_IMG_IDX+'" class="editImgUrl" style="margin-right:10px;">'+
				'<img id="editImg_a_img_'+EDIT_IMG_IDX+'" src="'+showImg+'" style="display:inline;height:100px;width:100px">'+
				'</a>'+
				'<a href="javascript:void(0)" onclick="delEditImg('+EDIT_IMG_IDX+')"">删除</a>'+
				'<a href="javascript:void(0)" style="margin-left:20px;" onclick="upImage('+EDIT_IMG_IDX+')"">上移</a>'+
				'</div>';
			$("#editItemThumb").append(imgHtml);// .val(res.data.url||'');
			// $('#delImgBtn_'+EDIT_IMG_IDX).linkbutton({
			// iconCls: 'icon-cancel'
			// });
    	}
    }
    option.imgExts = ['jpg','jpeg','png'];
    var uploader = new AjaxUploadEx(option);
}

// 移除副图图片
function delEditImg(idx){
	$("#editImg_"+idx).remove();
	var arrImgUrl=[];
	var arr=$("a.editImgUrl");
	for (var i = 0; i < arr.length; i++) {
		var imgUrl = $(arr[i]).attr('href');
		if(imgUrl&&imgUrl.length>0){
			arrImgUrl.push(imgUrl);
		}
	}
	$('#editItemThumb').html('');
	doSort(arrImgUrl);
}

// 向上移动图片
function upImage(idx){
	var tmp=$("#editImg_"+(idx-1));
	console.log(tmp);
	if(tmp!=null&&tmp.length>0){
		var a = $("#editImg_a_"+idx).attr('href'); 
		var b = $("#editImg_a_"+(idx-1)).attr('href'); 
		$("#editImg_a_"+(idx-1)+"").attr('href',a);
		$("#editImg_a_"+idx+"").attr('href',b);
		
		var ai = $("#editImg_a_img_"+idx).attr('src'); 
		var bi = $("#editImg_a_img_"+(idx-1)).attr('src'); 
		$("#editImg_a_img_"+(idx-1)+"").attr('src',ai);
		$("#editImg_a_img_"+idx+"").attr('src',bi);
	}else{
		$.messager.alert('提示信息','图片在第一张不用上移','warning');
	}
}

// 添加秒杀活动信息
function addActivityInfo(){
	$("#editTable").show();
	$('#editForm').form('clear');
	$('#editItemThumb').html('');
	$("#actId").val('');
	
	$("#editType").combobox('enable');
	//活动分类
	$("#editType").combobox({
		data:[{type_id:0,type_name:'不限'},{type_id:10,type_name:'秒杀活动'}],
		valueField:'type_id',
		textField:'type_name',
		value:0
	});
	$("#editBtn").show();
	$('#editDlg').window({
		title:'新建活动信息',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#editDlg').window('move',{top:20,left:20});
	$('#editDlg').window('open');
}

/**	
 * 提交修改编辑
 */
function doEdit(){
	var actId = $("#actId").val();//活动ID
	var type = $("#editType").combobox('getValue');
	var sDate = $("#queryDateStart").datetimebox('getValue');//开始日期
	var eDate = $("#queryDateEnd").datetimebox('getValue');
	if(type==null || Number(type||'0')<=0){
		$.messager.alert('提示信息','请选择一个活动分类！','info');
		return;
	}
	if(sDate==null || sDate.length<=0 || eDate==null || eDate.length<=0){
		$.messager.alert('提示信息','时间不能为空','info');
		return;
	}
	sDate = chkInputDate(sDate);
	if(sDate==null || sDate.length<=0){
		$.messager.alert('提示信息','请输入有效时间','info');
		return;
	}
	if(sDate<=eDate){
		var desc = $("#editDesc").val();
		var title = $("#editTitle").val();
		var actUrl = $("#actUrl").val();
		//保存配图数据
		var arrImgUrl = [];
		var arr = $("a.editImgUrl");
		 for(var i=0; i<arr.length; i++){
			var imgUrl = $(arr[i]).attr('href');
			if(imgUrl && imgUrl.length>0){
				arrImgUrl.push(imgUrl);
			}
		}
		 if(title && title.length>0) {
				var url='';
				var url = appPath+"/itbActivity/addActivityInfo.action";//新建
				if(Number(actId||'0')>0) {
					url = appPath+"/itbActivity/updActivityInfo.action";//修改
				}
				var sendData = {
					"activityInfoDto.act_id": actId||"",
					"activityInfoDto.type": type,
					"activityInfoDto.title": title || "",
					"activityInfoDto.start_time": sDate || "",
					"activityInfoDto.end_time": eDate || "",
					"activityInfoDto.desc": desc || "",
					"activityInfoDto.image": JSON.stringify(arrImgUrl),
					"activityInfoDto.url": actUrl || ""
				};
			    $.post(url, sendData, function(data){  
					if (data == "ok") { 
						$.messager.alert('提示信息','提交成功','info');
						$('#editDlg').window('close');
						doQuery();
			        }else {
			        	$.message.alert("提示信息","提交失败",'info');
			        }
			    });
				
		} else {
			$.messager.alert('提示信息','活动标题必须填写！','info');
		}	
	}else{
		$.messager.alert('提示信息','活动开始时间不能比结束时间大！','info');
	}
}
// 判断时间有效性
function chkInputDate(str){
	var reg = /^(\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;  
	var r = str.match(reg); 
	if(r==null)return '';  
	r[2]=r[2]-1;  
	var d= new Date(r[1], r[2],r[3], r[4],r[5], r[6]);  
	if(d.getFullYear()!=r[1])return '';  
	if(d.getMonth()!=r[2])return '';  
	if(d.getDate()!=r[3])return '';  
	if(d.getHours()!=r[4])return '';  
	if(d.getMinutes()!=r[5])return '';  
	if(d.getSeconds()!=r[6])return '';  
	return str;  
}

function cancelEdit(){
	$('#editDlg').window('close');
}

/**
 * 活动详情
 * @param id
 */
function showDetail(id){
	$("#editTable").show();
	$('#editForm').form('clear');
	$('#editItemThumb').html('');
	$("#actId").val(id);
	// 加载数据
	var url = appPath + "/itbActivity/getOneActivityInfo.action?actId="+id;
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#editDesc").val(info.desc||'');
			$("#editType").combobox({
				data:[{type_id:0,type_name:'不限'},{type_id:10,type_name:'秒杀活动'}],
				valueField:'type_id',
				textField:'type_name',
				value:info.type
			});
			$("#editTitle").val(info.title||'');
			$("#actUrl").val(info.url||'');
			$("#queryDateStart").datetimebox('setValue', info.start_time);
			$("#queryDateEnd").datetimebox('setValue',info.end_time);
			// 配图缩略图
			var arrImg = JSON.parse(info.image||'[]');
			doSort(arrImg);
		}
	});
	
	$("#editBtn").show();
	$('#editDlg').window({
		title:'活动详情',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#editDlg').window('move',{top:20,left:20});
	$('#editDlg').window('open');
}

// 附图图片展示
function doSort(arrImg){
	EDIT_IMG_IDX=0;
	for(var i=0; i<arrImg.length; i++){
		if(arrImg[i] && arrImg[i].length>0) {
			EDIT_IMG_IDX = Number(EDIT_IMG_IDX||0)+1;// 表示图片的位置// EDIT_IMG_IDX=0初始值
    		var showImg = arrImg[i]+'?x-oss-process=image/resize,m_pad,h_180,w_180,color_cccccc';
			var imgHtml = '<div style="margin:8px;" id="editImg_'+EDIT_IMG_IDX+'">'+
				'<a href="' +arrImg[i] + '" target="_blank" id="editImg_a_'+EDIT_IMG_IDX+'" class="editImgUrl" style="margin-right:10px;">'+
				'<img id="editImg_a_img_'+EDIT_IMG_IDX+'" src="'+showImg+'" style="display:inline;height:100px;width:100px">'+
				'</a>'+
				'<a href="javascript:void(0)" onclick="delEditImg('+EDIT_IMG_IDX+')"">删除</a>'+
				'<a href="javascript:void(0)" onclick="upImage('+EDIT_IMG_IDX+')" style="margin-left:20px;text-decoration:none;">上移</a>'+
				'</div>';
			$("#editItemThumb").append(imgHtml);
		}
	}
}

function cancelUpdTmpl(){
	$('#tmplDlg').window('close');
}

/**
 * 删除活动
 */
function delActInfo(){
	var selectItem=$("#actInfoGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择需要删除的内容！','warning');
		return;
	}
	$.messager.confirm("确认", "是否确认[删除]所选内容？",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectItem, function(index, item){
					ids = ids + item.act_id + ",";
				});
				if(ids){
					ids = ids.substring(0, ids.length-1);
					var url = appPath+"/itbActivity/delActivityInfo.action?ids="+ids;
					$.post(url,function(data){
						if(data=="ok"){
							$.messager.alert('提示信息','删除成功','info');
							doQuery();
						}else{
							$.messager.alert('提示信息','删除失败','info');
						}
					});
				}
				
	        }
		}
	);
}

/**
 * 获取参数
 */
function getQueryParam(){
	var queryObject = {};
	var findType = $("#boType").combobox('getValue');
	if(findType && findType.length>0 && Number(findType)>0) queryObject.findType=findType;
	var findState = $("#boState").combobox('getValue');
	if(findState && findState.length>0 && Number(findState)>0)queryObject.findState=findState;
	var findPu = $("#boPublish").combobox('getValue');
	if(findPu && findPu.length>0 && Number(findPu)>=0)queryObject.findPu=findPu;
	var title = $("#queryTitle").val();
	if(title && title.length>0) queryObject.findTitle=title;
	return queryObject;
}

/**查询活动*/
function doQuery(startFlg){
	$("#actInfoGrid").datagrid('unselectAll');
	if(startFlg==1){
		$("#actInfoGrid").datagrid('load', getQueryParam());
	} else {
		$("#actInfoGrid").datagrid('reload', getQueryParam());
	}
}

/**查询活动商品*/
function doQuery2(startFlg){
	$("#actItemGrid").datagrid('unselectAll');
	if(startFlg==1){
		$("#actItemGrid").datagrid('load', getQueryParam());
	} else {
		$("#actItemGrid").datagrid('reload', getQueryParam());
	}
}
